package com.jdy.haoduoai.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class FileUtils {

  public FileUtils(Context context, String local_image_path) {
    this.local_image_path = local_image_path;
  }

  public static void openFile(File file, Activity context) {
    

  }

  private static final String TAG = FileUtils.class.getSimpleName();
  private String local_image_path;

  /* Checks if external storage is available for read and write */
  public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
      return true;
    }
    return false;
  }

  /**
   * 保存图片到制定路径
   * 
   * @param filepath
   * @param bitmap
   */
  public void saveBitmap(String filename, Bitmap bitmap) {
    if (!isExternalStorageWritable()) {
      Log.i(TAG, "SD卡不可用，保存失败");
      return;
    }

    if (bitmap == null) {
      return;
    }

    try {

      File file = new File(local_image_path, filename);
      FileOutputStream outputstream = new FileOutputStream(file);
      if ((filename.indexOf("png") != -1) || (filename.indexOf("PNG") != -1)) {
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputstream);
      } else {
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputstream);
      }

      outputstream.flush();
      outputstream.close();

    } catch (FileNotFoundException e) {
      Log.i(TAG, e.getMessage());
    } catch (IOException e) {
      Log.i(TAG, e.getMessage());
    }
  }

  /**
   * 返回当前应用 SD 卡的绝对路径 like /storage/sdcard0/Android/data/com.example.test/files
   */
  @SuppressLint("SdCardPath")
  public String getAbsolutePath() {
    File root = new File(local_image_path);
    if (!root.exists()) {
      root.mkdirs();

    }

    return local_image_path;

  }

  @SuppressLint("SdCardPath")
  public boolean isBitmapExists(String filename) {
    File dir = new File(local_image_path);
    if (!dir.exists()) {
      dir.mkdirs();
    }
    // context.getExternalFilesDir(null);
    File file = new File(dir, filename);

    return file.exists();
  }

  /*
   * Create folder in external storage.
   */
  public static boolean CreateFolder(String folderName) {
    File folder = new File(Environment.getExternalStorageDirectory()
        .getAbsolutePath() + "/" + folderName);
    boolean success = true;
    if (!folder.exists()) {
      success = folder.mkdir();
    }
    return success;
  }

  /**
   * 需要知道当前SD卡的目录，Environment.getExternalStorageDierctory()
   */

  private String SDPATH;

  public String getSDPATH() {
    return SDPATH;
  }

  public FileUtils() { // 目录名/sdcard
    SDPATH = Environment.getExternalStorageDirectory() + "/";
  }

  // 在sdcard卡上创建文件
  public File createSDFile(String fileName) throws IOException {
    File file = new File(SDPATH + fileName);
    file.createNewFile();
    return file;
  }

  // 在sd卡上创建目录
  public File createSDDir(String dirName) {
    File dir = new File(SDPATH + dirName);
    // mkdir只能创建一级目录 ,mkdirs可以创建多级目录
    dir.mkdir();
    return dir;
  }

  // 判断sd卡上的文件夹是否存在
  public boolean isFileExist(String fileName) {
    File file = new File(SDPATH + fileName);
    return file.exists();
  }

  /**
   * 将一个inputstream里面的数据写入SD卡中 第一个参数为目录名 第二个参数为文件名
   */
  public File write2SDFromInput(String path, String fileName,
      InputStream inputstream) {
    File file = null;
    OutputStream output = null;
    try {
      createSDDir(path);
      // System.out.println(createSDDir(path).getParentFile());
      file = createSDFile(path + fileName);
      output = new FileOutputStream(file);
      // 4k为单位，每4K写一次
      byte buffer[] = new byte[4 * 1024];
      int temp = 0;
      while ((temp = inputstream.read(buffer)) != -1) {
        // 获取指定信,防止写入没用的信息
        output.write(buffer, 0, temp);
      }
      output.flush();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (output != null) {
          output.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    return file;
  }

  public static String convertStreamToString(InputStream is) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
      sb.append(line).append("\n");
    }
    reader.close();
    return sb.toString();
  }

  public static String readFileToString(File fl) {
    
    FileInputStream fin;
    try {
      fin = new FileInputStream(fl);
      String ret = convertStreamToString(fin);
      // Make sure you close all streams.
      fin.close();
      return ret;
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return null;
  }
}
